package com.jsz.peini.service.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.jsz.peini.bean.order.OrderSeller;
import com.jsz.peini.bean.order.OrderSellerExample;
import com.jsz.peini.bean.seller.SellerDiscount;
import com.jsz.peini.bean.seller.SellerDiscountExample;
import com.jsz.peini.bean.seller.SellerDiscountExample.Criteria;
import com.jsz.peini.bean.seller.SellerInfo;
import com.jsz.peini.bean.task.TaskCancelFlow;
import com.jsz.peini.bean.task.TaskCancelFlowExample;
import com.jsz.peini.bean.task.TaskInfo;
import com.jsz.peini.bean.task.TaskInfoExample;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.util.AppPush;
import com.jsz.peini.common.util.CommonUtils;
import com.jsz.peini.common.util.DateTimeUtils;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.common.util.SmsSendUtil;
import com.jsz.peini.emchat.api.EasemobMessages;
import com.jsz.peini.mapper.order.OrderInfoMapper;
import com.jsz.peini.mapper.order.OrderSellerMapper;
import com.jsz.peini.mapper.seller.SellerDiscountMapper;
import com.jsz.peini.mapper.seller.SellerInfoMapper;
import com.jsz.peini.mapper.task.PartyInfoMapper;
import com.jsz.peini.mapper.task.TaskCancelFlowMapper;
import com.jsz.peini.mapper.task.TaskInfoMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.mapper.user.UserSmsMapper;
import com.jsz.peini.redis.util.TaskRedisUtil;
import com.jsz.peini.server.thread.UserSquareThread;
import com.jsz.peini.server.thread.taskTimertask;
import com.jsz.peini.service.user.UserInfoService;
import com.jsz.peini.sms.SmsSend;
import com.jsz.peini.vo.CommonTaskInfo;
import com.jsz.peini.vo.TaskInMapSearchVo;
import com.jsz.peini.vo.UserConcerVo;

@Service
public class TaskInfoService {
	private static final Logger logger = LoggerFactory.getLogger(TaskInfoService.class);
	@Resource
	private TaskInfoMapper taskInfoMapper;
	@Resource
	private SellerDiscountMapper sellerDiscountMapper;
	@Resource
	private SellerInfoMapper sellerInfoMapper;
	@Resource
	private UserInfoService userInfoService;
	@Resource
	private UserInfoMapper userInfoMapper;
	@Resource
	private UserSmsMapper userSmsMapper;
	@Resource
	private OrderInfoMapper orderInfoMapper;
	@Resource
	private OrderSellerMapper orderSellerMapper;
	@Resource
	private TaskCancelFlowMapper taskCancelFlowMapper;
	@Resource
	private PartyInfoMapper partyInfoMapper;

	//任务预定通知id
	private static final String SMSTaskFrom = "39779"; 
	
	@Transactional
	public LinkedHashMap<String, Object> setTaskInfo(HttpServletRequest request,
			String userId,
			Integer taskProvince,
			Integer taskCity,
			Integer sellerInfoId,
			String taskAppointedTime,
			String taskDesc,
			Integer otherSex,//1男；2女；3不限
			Integer otherLowAge,//如果年龄不限为空
			Integer otherHignAge,//如果年龄不限为空
			Integer otherBuy,
			Integer otherGo,
			String xpoint,
			String ypoint
			) {
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try {
			
			Date pointTime = DateTimeUtils.formatString2Date(taskAppointedTime, "yyyy-MM-dd HH:mm");
			
			TaskInfo taskInfo = new TaskInfo();
			taskInfo.setUserId(userId);
			taskInfo.setTaskProvince(taskProvince);
			taskInfo.setTaskCity(taskCity);
			taskInfo.setSellerInfoId(sellerInfoId);
			
			SellerDiscountExample disExample = new SellerDiscountExample();
			Criteria criteria = disExample.createCriteria();
			criteria.andSellerInfoIdEqualTo(sellerInfoId);
			List<SellerDiscount> disList = sellerDiscountMapper.selectByExample(disExample);
			if(disList.size() == 0){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "您选择的时间店铺不营业!");
				return infoMap;
			}
			
			SellerDiscount sellerDiscount = null;
			int weekNum = CommonUtils.getWeekNum(pointTime);
			for (SellerDiscount discount : disList) {
				if(discount.getStartNum()<= weekNum && discount.getEndNum() >= weekNum){
					
					String start = discount.getStartTime();
					String end = discount.getEndTime();
					
					String taskPStr = taskAppointedTime.substring(taskAppointedTime.indexOf(" ")+1, taskAppointedTime.length()).replace(" ", "");
					
					Date startD = DateTimeUtils.formatString2Date(start, "HH:mm");
					Date endD = DateTimeUtils.formatString2Date(end, "HH:mm");
					Date pointD = DateTimeUtils.formatString2Date(taskPStr, "HH:mm");
					Date centerD = DateTimeUtils.formatString2Date("23:59", "HH:mm");
					
					if(startD.before(endD)){
						if((pointD.after(startD) && pointD.before(endD)) || taskPStr.equals(start) 
								|| taskPStr.equals(end)){
							sellerDiscount = discount;
						}
					}else{
						if((pointD.after(startD) && pointD.before(centerD)) || taskPStr.equals(start) 
								|| taskPStr.equals(end) || taskPStr.equals("00:00") 
								|| (pointD.after(DateTimeUtils.formatString2Date("00:00", "HH:mm")) && pointD.before(endD))){
							sellerDiscount = discount;
						}
					}
				}
			}
			if(sellerDiscount == null){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "您选择的时间店铺不营业!");
				return infoMap;
			}
			
			SellerInfo sellerInfo = sellerInfoMapper.selectByPrimaryKey(sellerInfoId);
			taskInfo.setSellerInfoName(sellerInfo.getSellerName());
			taskInfo.setSellerBigType(sellerInfo.getSellerType());
			taskInfo.setSellerSmallType(Integer.parseInt(sellerInfo.getLabelsId()));
			taskInfo.setTaskTime(new Date());
			taskInfo.setTaskStatus(1);
			
			taskInfo.setTaskAppointedTime(pointTime);
			taskInfo.setTaskDesc(taskDesc);
			taskInfo.setOtherSex(otherSex);
			taskInfo.setOtherLowAge(otherLowAge);
			taskInfo.setOtherHignAge(otherHignAge);
			taskInfo.setOtherBuy(otherBuy);
			taskInfo.setOtherGo(otherGo);
			taskInfo.setXpoint(sellerInfo.getXpoint() == null ? "0" : sellerInfo.getXpoint());
			taskInfo.setYpoint(sellerInfo.getYpoint() == null ? "0" : sellerInfo.getYpoint());
			
			if (taskInfo != null) {
				int setTaskInfoNum = taskInfoMapper.insertSelective(taskInfo);
				if (setTaskInfoNum > 0) {
					
					//将任务写入redis缓存
					List<LinkedHashMap<String, Object>> taskList = taskInfoMapper.selectByALL(taskInfo);
					for (LinkedHashMap<String, Object> taskMap : taskList) {
						TaskRedisUtil.addTaskToRedis(taskMap);
					}
					
					int taskNum = userInfoService.getTaskNum(taskInfo.getUserId(), +3);
					UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
					userInfo.setTaskNum(taskNum);
					userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
					userInfoMapper.updateByPrimaryKey(userInfo);
					HashMap<String,Object> task=taskInfoMapper.getTaskLast(taskInfo.getUserId());
					
					SmsSendUtil.sendSmsNotify(taskInfo.getUserId(), task.get("taskId").toString(), 103, "恭喜您！发布任务成功！奖励您任务经验3分~");
					
					UserInfo newuserInfo2 = userInfoMapper.selectByPrimaryKey(userId);
					UserConcerVo concerVo = new UserConcerVo(newuserInfo2.getId(), (long)taskInfo.getId(), null, 2, newuserInfo2.getNickname(), newuserInfo2.getAccCode(), newuserInfo2.getSignWord());
					/*newuserInfo2.setBytype(2);
					newuserInfo2.setSignWord(taskInfo.getId().toString());*/
					UserSquareThread.userInfo.add(concerVo);
					
					//消息推送
					JSONObject object = new JSONObject();
					object.put("title", "任务发布成功");
					object.put("content", "恭喜您！发布任务成功！奖励您任务经验3分~");
					object.put("paramId", task.get("taskId").toString());
					object.put("type", 103);
					UserInfo newuserInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
					AppPush.sendPush(object,newuserInfo.getUserPhone().split(","));
					
					infoMap.put("resultCode", Constants.SUCCESS);
					infoMap.put("resultDesc", "任务发布成功");
				}
			}
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
			throw e;
		}
		return infoMap;
	}
	
	public List<LinkedHashMap<String,Object>> selectByALL(TaskInfo taskInfo) {
		List<LinkedHashMap<String,Object>> taskList = taskInfoMapper.selectByALL(taskInfo);
		return taskList;
	}
	
	public List<LinkedHashMap<String,Object>> selectTaskInfoBySort(TaskInfo taskInfo) {
		List<LinkedHashMap<String,Object>> taskList = taskInfoMapper.selectTaskInfoBySort(taskInfo);
		return taskList;
	}

	public int setTaskInfo(TaskInfo taskInfo){
		int taskInfoNum=taskInfoMapper.setTaskInfo(taskInfo);
		return taskInfoNum;
	}
	
	public List<LinkedHashMap<String,Object>> getTaskInfo(TaskInfo taskInfo){
		List<LinkedHashMap<String,Object>> taskInfoList = taskInfoMapper.getTaskInfo(taskInfo);
		return taskInfoList;
	}
	
	@Transactional
	public int updateTaskInfo(TaskInfo taskInfo,UserInfo otherInfo,String userId){
		int taskInfoNum = taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
		if (taskInfoNum > 0) {
			//消息推送
			JSONObject object = new JSONObject();
	        object.put("title", "任务接取通知");
	        object.put("type", 1);
	        object.put("paramId", taskInfo.getId());
	        
	        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
	        UserInfo newuserInfo = userInfoMapper.selectByPrimaryKey(userId);
	        object.put("content", ""+PeiniUtils.updateNickName(newuserInfo.getNickname(), newuserInfo.getAccCode())+"接取了您的任务！快去和TA进行沟通吧~");
	        AppPush.sendPush(object,userInfo.getUserPhone().split(","));
	        
			object.put("content", "您已接取了“"+PeiniUtils.updateNickName(userInfo.getNickname(), userInfo.getAccCode())+"”任务！快去和TA进行沟通吧~");
			AppPush.sendPush(object,newuserInfo.getUserPhone().split(","));
			
	        //给发起人推送消息
			SmsSendUtil.sendSmsNotify(taskInfo.getUserId(), taskInfo.getId().toString(), 1, ""+PeiniUtils.updateNickName(newuserInfo.getNickname(), newuserInfo.getAccCode())+"接取了您的任务！快去和TA进行沟通吧~");
			SmsSendUtil.sendSmsNotify(taskInfo.getOtherUserId(), taskInfo.getId().toString(), 1, "您已接取了“"+PeiniUtils.updateNickName(userInfo.getNickname(), userInfo.getAccCode())+"”任务！快去和TA进行沟通吧~");
	        
	        UserInfo taskUserInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
			UserInfo taskOtherInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getOtherUserId());
			
			OrderSeller orderSeller = new OrderSeller();
			orderSeller.setTaskUserId(taskInfo.getUserId());
			orderSeller.setTaskOtherId(userId);
			orderSeller.setOrderStatus(0);
			orderSeller.setTaskId((long)taskInfo.getId());
			orderSeller.setSellerId((long)taskInfo.getSellerInfoId());
			orderSeller.setOrderTime(new Date());
			orderSeller.setOrderType(1);
			orderSeller.setOtherBy(taskInfo.getOtherBuy());
			orderSeller.setUserId(taskInfo.getUserId());
			orderSeller.setOtherId(taskInfo.getOtherUserId());
			switch (taskInfo.getOtherBuy()) {
			case 1://我买单
			case 2://他买单
			case 3://AA
				orderSeller.setUserImageHead(taskUserInfo.getImageHead());
				orderSeller.setUserNickname(taskUserInfo.getNickname());
				orderSeller.setOtherImageHead(taskOtherInfo.getImageHead());
				orderSeller.setOtherNickname(taskOtherInfo.getNickname());
			default:
				break;
			}
			orderSellerMapper.insert(orderSeller);	
			
			String code = "";
			code += orderSeller.getOrderType();
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
			code += sdf.format(new Date());
			String codeStr = String.valueOf(orderSeller.getId());
			if(codeStr.length()> 6){
				codeStr = codeStr.substring(codeStr.length()-6);
			}else if(codeStr.length() < 6){
				for (int i = 0; i < 6-codeStr.length(); i++) {
					code += "0";
				}
			}
			code += codeStr;
			orderSeller.setOrderCode(code);
			
			orderSellerMapper.updateByPrimaryKey(orderSeller);
			
			//给商家推送消息
			
			SmsSendUtil.sendSmsNotify(taskInfo.getSellerInfoId().toString(), orderSeller.getId().toString(), 21, "刚刚有人下单啦！(订单号<a href='seller/orderDetail?orderId="+orderSeller.getId()+"'>"+orderSeller.getOrderCode()+"</a>)");
			
			SellerInfo sellerInfo=sellerInfoMapper.getSellerInfoById(taskInfo.getSellerInfoId());
			SimpleDateFormat timeFormater = new SimpleDateFormat("MM-dd HH:mm");
			String str = timeFormater.format(taskInfo.getTaskAppointedTime());
			
			if(sellerInfo.getSmsType() != null && sellerInfo.getSmsType().indexOf("1")>=0){
				if (sellerInfo.getWeathersms()==1) {
					if (sellerInfo.getSmsText()!=null) {
						String param=orderSeller.getOrderCode()+","+sellerInfo.getSellerName()+"（"+sellerInfo.getDistrictName()+"店）,"+str;
						SmsSend.sendByTask(sellerInfo.getSmsText(), param, SMSTaskFrom);
					}
				}
			}
			//从redis缓存中移除该任务
			TaskRedisUtil.delTaskInfo(taskInfo.getId().toString());
		}
//		
//		int taskInfoNum = taskInfoMapper.updateTaskInfo(taskInfo);
		return taskInfoNum;
	}
	
	@Transactional
	public LinkedHashMap<String,Object> cancelTaskInfo(TaskInfo taskInfo,String userId,Integer taskId,Integer cancleType){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		//TODO 短信模版ID
		final String SMSTaskFromID ="42897";
		if(taskInfo.getTaskStatus() == 1){//没有任何人参加，扣除发布积分
			if(taskInfo.getUserId().equals(userId)){
				taskInfo.setTaskStatus(5);
				taskInfo.setTaskOtherStatus(5);
				taskInfo.setTaskCancleTime(new Date());
				taskInfo.setTaskCancleType(1);
				taskInfo.setCancelUserId(userId);
				
				taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
				
				//更新信用值和任务取消次数
				UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
				int taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
				if (taskNum-3 >= 1000) {
					userInfo.setTaskNum(1000);
				}else{
					userInfo.setTaskNum(taskNum-3);
				}
				userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
				int cancelCnt = userInfo.getTaskCancleCnt() == null ? 0 : userInfo.getTaskCancleCnt();
				userInfo.setTaskCancleCnt(cancelCnt+1);
				userInfoMapper.updateByPrimaryKeySelective(userInfo);
				
				//userInfoService.updateUserInfoTaskNumByPlusAndMinus(taskInfo.getUserId(), -3);
				//userInfoService.updateCredit(taskInfo.getUserId());
				
				TaskCancelFlow flow = new TaskCancelFlow();
				flow.setFlowId(UUID.randomUUID().toString().replace("-", ""));
				flow.setFromId(userId);
				flow.setIsFinish(1);
				flow.setSendTime(new Date());
				flow.setTaskId(taskId);
				taskCancelFlowMapper.insertSelective(flow);
				
				OrderSellerExample orSellerExample = new OrderSellerExample();
				com.jsz.peini.bean.order.OrderSellerExample.Criteria orCriteria = orSellerExample.createCriteria();
				orCriteria.andSellerIdEqualTo((long)taskInfo.getSellerInfoId());
				orCriteria.andOrderTypeEqualTo(1);
				orCriteria.andTaskIdEqualTo((long)taskId);
				orCriteria.andOrderStatusLessThanOrEqualTo(1);
				List<OrderSeller> list = orderSellerMapper.selectByExample(orSellerExample);
				if(list.size() > 0){
					OrderSeller orderSeller = list.get(0);
					orderSeller.setOrderStatus(-1);
					orderSellerMapper.updateByPrimaryKey(orderSeller);
				}
				
				//消息推送
				JSONObject object = new JSONObject();
		        object.put("title", "任务取消通知");
		        object.put("content", "“"+taskInfo.getSellerInfoName()+"”任务取消成功！由于您个人原因取消任务，扣除任务经验3分~");
		        object.put("type", 4);
		        object.put("paramId", taskInfo.getId());
		        
		        AppPush.sendPush(object,userInfoMapper.selectByPrimaryKey(userId).getUserPhone().split(","));
		        SmsSendUtil.sendSmsNotify(userId, taskId.toString(), 4, "“"+taskInfo.getSellerInfoName()+"”任务取消成功！由于您个人原因取消任务，扣除任务经验3分~");
		        
				//从redis缓存中删除
				TaskRedisUtil.delTaskInfo(taskId.toString());
				
				infoMap.put("resultCode", Constants.SUCCESS);
				infoMap.put("resultDesc", Constants.SUCCESS_DESC);
				return infoMap;
			}else{
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "这不是您发布的任务");
				return infoMap;
			}
		}else if(taskInfo.getTaskStatus() == 2){//已经有人参与，协商
			if(cancleType == null && cancleType != 1 && cancleType != 2){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "请输入取消原因类型");
				return infoMap;
			}
			if(cancleType == 1){//个人原因取消
				taskInfo.setTaskStatus(5);
				taskInfo.setTaskOtherStatus(5);
				taskInfo.setTaskCancleTime(new Date());
				taskInfo.setTaskCancleType(1);
				taskInfo.setCancelUserId(userId);					
				taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
				
				TaskCancelFlow flow = new TaskCancelFlow();
				flow.setFlowId(UUID.randomUUID().toString().replace("-", ""));
				flow.setFromId(userId);
				flow.setIsFinish(1);
				flow.setSendTime(new Date());
				flow.setTaskId(taskId);
				taskCancelFlowMapper.insertSelective(flow);
				
				if(taskInfo.getUserId().equals(userId)){//发起人取消
					//更新信用值和任务取消次数
					UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
					int taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
					if (taskNum-6 >= 1000) {
						userInfo.setTaskNum(1000);
					}else{
						userInfo.setTaskNum(taskNum-6);
					}
					userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
					int cancelCnt = userInfo.getTaskCancleCnt() == null ? 0 : userInfo.getTaskCancleCnt();
					userInfo.setTaskCancleCnt(cancelCnt+1);
					userInfoMapper.updateByPrimaryKeySelective(userInfo);
					
					//消息推送
					JSONObject object = new JSONObject();
			        object.put("title", "任务取消通知");
			        object.put("content", "“"+taskInfo.getSellerInfoName()+"”任务取消成功！由于您个人原因取消任务，将收回任务发布时赠送的任务经验3分，并额外扣除您任务经验3分~");
			        object.put("type", 4);
			        object.put("paramId", taskInfo.getId());
			        UserInfo u2 = userInfoMapper.selectByPrimaryKey(userId);
			        AppPush.sendPush(object,u2.getUserPhone().split(","));
			        SmsSendUtil.sendSmsNotify(userId, taskId.toString(), 4, "“"+taskInfo.getSellerInfoName()+"”任务取消成功！由于您个人原因取消任务，将收回任务发布时赠送的任务经验3分，并额外扣除您任务经验3分~");
			        
			        object.put("content", "“"+taskInfo.getSellerInfoName()+"”任务取消成功！由于对方放弃本次任务，任务取消~不要气馁，让我们继续约起来~下一个可能更好哦~");
			        AppPush.sendPush(object,userInfoMapper.selectByPrimaryKey(taskInfo.getOtherUserId()).getUserPhone().split(","));
			        SmsSendUtil.sendSmsNotify(taskInfo.getOtherUserId(), taskId.toString(), 4, "“"+taskInfo.getSellerInfoName()+"”任务取消成功！由于对方放弃本次任务，任务取消~不要气馁，让我们继续约起来~下一个可能更好哦~");			        
				}else{//接收人取消
					//更新信用值和任务取消次数
					UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
					int taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
					if (taskNum-3 >= 1000) {
						userInfo.setTaskNum(1000);
					}else{
						userInfo.setTaskNum(taskNum-3);
					}
					userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
					int cancelCnt = userInfo.getTaskCancleCnt() == null ? 0 : userInfo.getTaskCancleCnt();
					userInfo.setTaskCancleCnt(cancelCnt+1);
					userInfoMapper.updateByPrimaryKeySelective(userInfo);
					
					//消息推送
					JSONObject object = new JSONObject();
			        object.put("title", "任务取消通知");
			        object.put("content", "“"+taskInfo.getSellerInfoName()+"”任务取消成功！由于您个人原因取消任务，扣除任务经验3分~");
			        object.put("type", 4);
			        object.put("paramId", taskInfo.getId());
			        UserInfo u2 = userInfoMapper.selectByPrimaryKey(userId);
			        AppPush.sendPush(object,u2.getUserPhone().split(","));
			        SmsSendUtil.sendSmsNotify(userId, taskId.toString(), 4, "“"+taskInfo.getSellerInfoName()+"”任务取消成功！由于您个人原因取消任务，扣除任务经验3分~");
			        
			        object.put("content", "“"+taskInfo.getSellerInfoName()+"”任务取消成功！由于对方放弃本次任务，任务取消~不要气馁，让我们继续约起来~下一个可能更好哦~");
			        AppPush.sendPush(object,userInfoMapper.selectByPrimaryKey(taskInfo.getUserId()).getUserPhone().split(","));
			        SmsSendUtil.sendSmsNotify(taskInfo.getUserId(), taskId.toString(), 4, "“"+taskInfo.getSellerInfoName()+"”任务取消成功！由于对方放弃本次任务，任务取消~不要气馁，让我们继续约起来~下一个可能更好哦~");
				}
				 SellerInfo sellerInfo=sellerInfoMapper.getSellerInfoById(taskInfo.getSellerInfoId());
					if(StringUtils.isNotBlank(sellerInfo.getSmsType()) && sellerInfo.getSmsType().indexOf("2")>=0){
						OrderSellerExample orSellerExample = new OrderSellerExample();
						com.jsz.peini.bean.order.OrderSellerExample.Criteria orCriteria = orSellerExample.createCriteria();
						orCriteria.andSellerIdEqualTo((long)taskInfo.getSellerInfoId());
						orCriteria.andOrderTypeEqualTo(1);
						orCriteria.andTaskIdEqualTo((long)taskId);
						orCriteria.andOrderStatusLessThanOrEqualTo(1);
						List<OrderSeller> list = orderSellerMapper.selectByExample(orSellerExample);
						if(list.size() > 0){
							OrderSeller orderSeller = list.get(0);
							orderSeller.setOrderStatus(-1);
							orderSellerMapper.updateByPrimaryKey(orderSeller);
						if (sellerInfo.getWeathersms()==1) {
							if (sellerInfo.getSmsText()!=null) {
								String param=orderSeller.getOrderCode()+","+sellerInfo.getSellerName()+"（"+sellerInfo.getDistrictName()+"店）,";
								SmsSend.sendByTask(sellerInfo.getSmsText(), param, SMSTaskFromID);
							}
						}
						}
					}
		        OrderSellerExample orSellerExample = new OrderSellerExample();
				com.jsz.peini.bean.order.OrderSellerExample.Criteria orCriteria = orSellerExample.createCriteria();
				orCriteria.andSellerIdEqualTo((long)taskInfo.getSellerInfoId());
				orCriteria.andOrderTypeEqualTo(1);
				orCriteria.andTaskIdEqualTo((long)taskId);
				orCriteria.andOrderStatusLessThanOrEqualTo(1);
				List<OrderSeller> list = orderSellerMapper.selectByExample(orSellerExample);
				if(list.size() > 0){
					OrderSeller orderSeller = list.get(0);
					orderSeller.setOrderStatus(-1);
					orderSellerMapper.updateByPrimaryKey(orderSeller);
				}
				
				//从redis缓存中删除
				TaskRedisUtil.delTaskInfo(taskId.toString());
				
				infoMap.put("resultCode", Constants.SUCCESS);
				infoMap.put("resultDesc", Constants.SUCCESS_DESC);
				return infoMap;
			}else{//双方协商
				if(taskInfo.getUserId().equals(userId)){//发起人取消，向参与人推送消息协商
					UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
					UserInfo otherInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getOtherUserId());				        
					
			        //查询是否已经申请过了，对方未处理
			        TaskCancelFlowExample example = new TaskCancelFlowExample();
			        com.jsz.peini.bean.task.TaskCancelFlowExample.Criteria criteria = example.createCriteria();
			        criteria.andFromIdEqualTo(userId);
			        criteria.andToidEqualTo(taskInfo.getOtherUserId());
			        criteria.andTaskIdEqualTo(taskId);
			        criteria.andIsFinishEqualTo(0);
			        List<TaskCancelFlow> flowList = taskCancelFlowMapper.selectByExample(example);
			        if(flowList.size() > 0){
			        	TaskCancelFlow hisFlow = flowList.get(0);
			        	Date now = new Date();
			        	long diff = now.getTime() - hisFlow.getSendTime().getTime();
			        	long hours = diff / (1000 * 60 * 60);
			        	if(hours >= 24){//自动取消成功
			        		taskInfo.setTaskStatus(5);
			        		taskInfo.setTaskOtherStatus(5);
							taskInfo.setTaskCancleTime(new Date());
							taskInfo.setTaskCancleType(2);
							taskInfo.setCancelUserId(taskInfo.getOtherUserId());					
							taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
							
							hisFlow.setIsFinish(1);
							hisFlow.setRecvTime(new Date());
							taskCancelFlowMapper.updateByPrimaryKeySelective(hisFlow);
							
							//更新信用值和任务取消次数
							int taskNum = otherInfo.getTaskNum() == null ? 0 : otherInfo.getTaskNum();
							if (taskNum-3 >= 1000) {
								otherInfo.setTaskNum(1000);
							}else{
								otherInfo.setTaskNum(taskNum-3);
							}
							otherInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
							int cancelCnt = otherInfo.getTaskCancleCnt() == null ? 0 : otherInfo.getTaskCancleCnt();
							otherInfo.setTaskCancleCnt(cancelCnt+1);
							userInfoMapper.updateByPrimaryKeySelective(otherInfo);
							
							//消息推送
							JSONObject object = new JSONObject();
					        object.put("title", "任务自动取消通知");
					        object.put("content", "由于您超过24小时未处理对方的任务取消请求，系统自动取消成功，扣除您任务经验3分");
					        object.put("type", 5);
					        object.put("paramId", taskInfo.getId());
					        
							AppPush.sendPush(object,otherInfo.getUserPhone().split(","));
							
							SmsSendUtil.sendSmsNotify(otherInfo.getId(), taskId.toString(), 5, "由于您超过24小时未处理对方的任务取消请求，系统自动取消成功，扣除您任务经验3分");
							
							//消息推送
					        object.put("content", "由于对方24小时未处理您的任务取消请求，系统自动取消成功");
					        
							AppPush.sendPush(object,userInfo.getUserPhone().split(","));
							
							SmsSendUtil.sendSmsNotify(userInfo.getId(), taskId.toString(), 5, "由于对方24小时未处理您的任务取消请求，系统自动取消成功");
							
							//从redis缓存中删除
							TaskRedisUtil.delTaskInfo(taskId.toString());
							
							infoMap.put("resultCode", Constants.SUCCESS);
							infoMap.put("resultDesc", Constants.SUCCESS_DESC);
							taskTimertask t=new taskTimertask();
							t.setTaskId(taskId);
							t.setType(1);
							t.setUserId(userId);
							t.taskend();
							return infoMap;
			        	}else{
			        		infoMap.put("resultCode", Constants.FAIL);
			        		infoMap.put("resultDesc", "您上次的取消请求对方尚未处理");
			        		return infoMap;
			        	}
			        }else{
			        	TaskCancelFlow flow = new TaskCancelFlow();
						flow.setFlowId(UUID.randomUUID().toString().replace("-", ""));
						flow.setFromId(userId);
						flow.setIsFinish(0);
						flow.setSendTime(new Date());
						flow.setTaskId(taskId);
						flow.setToid(taskInfo.getOtherUserId());
						taskCancelFlowMapper.insertSelective(flow);
						
						String from = userInfo.getUserPhone();
						
						//环信发送消息
						JSONObject object = new JSONObject();
						object.put("from", from);
				        object.put("title", "任务取消通知");
				        object.put("type", 2);
				        object.put("paramId", taskInfo.getId());
				        object.put("content", "双方协商取消任务");
				        
						AppPush.sendPush(object,otherInfo.getUserPhone().split(","));
						
						JsonNodeFactory factory = new JsonNodeFactory(false);
						//String from = userMap.get("mobileNo").toString();
				        String targetTypeus = "users";
				        ObjectNode ext = factory.objectNode();
				        ArrayNode targetusers = factory.arrayNode();
				        targetusers.add(otherInfo.getUserPhone());
				        ObjectNode cmdmsg = factory.objectNode();
				        cmdmsg.put("action", object.toJSONString());
				        cmdmsg.put("type","cmd");
				        ObjectNode sendTxtMessageusernode = EasemobMessages.sendMessages(targetTypeus, targetusers, cmdmsg, from, null);
				        
						SmsSendUtil.sendSmsNotify(userId,otherInfo.getId().toString(), taskInfo.getId().toString(), 2, "双方协商取消任务!");
						
						taskTimertask t=new taskTimertask();
						t.setTaskId(taskId);
						t.setType(1);
						t.setUserId(userId);
						t.taskend();
				        infoMap.put("resultCode", Constants.SUCCESS);
						infoMap.put("resultDesc", Constants.SUCCESS_DESC);
						return infoMap;
			        }
				}else if(taskInfo.getOtherUserId().equals(userId)){//参与人取消，向发起人推送
					UserInfo otherInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
					UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
			        //查询是否已经申请过了，对方未处理
			        TaskCancelFlowExample example = new TaskCancelFlowExample();
			        com.jsz.peini.bean.task.TaskCancelFlowExample.Criteria criteria = example.createCriteria();
			        criteria.andFromIdEqualTo(userId);
			        criteria.andToidEqualTo(taskInfo.getUserId());
			        criteria.andTaskIdEqualTo(taskId);
			        criteria.andIsFinishEqualTo(0);
			        List<TaskCancelFlow> flowList = taskCancelFlowMapper.selectByExample(example);
			        if(flowList.size() > 0){
			        	TaskCancelFlow hisFlow = flowList.get(0);
			        	Date now = new Date();
			        	long diff = now.getTime() - hisFlow.getSendTime().getTime();
			        	long hours = diff / (1000 * 60 * 60);
			        	if(hours >= 24){//自动取消成功
			        		taskInfo.setTaskStatus(5);
			        		taskInfo.setTaskOtherStatus(5);
							taskInfo.setTaskCancleTime(new Date());
							taskInfo.setTaskCancleType(2);
							taskInfo.setCancelUserId(taskInfo.getUserId());					
							taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
							
							hisFlow.setIsFinish(1);
							hisFlow.setRecvTime(new Date());
							taskCancelFlowMapper.updateByPrimaryKeySelective(hisFlow);
							
							//更新信用值和任务取消次数
							//UserInfo userInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
							int taskNum = otherInfo.getTaskNum() == null ? 0 : otherInfo.getTaskNum();
							if (taskNum-3 >= 1000) {
								otherInfo.setTaskNum(1000);
							}else{
								otherInfo.setTaskNum(taskNum-3);
							}
							otherInfo.setReputation(PeiniUtils.getCredit(otherInfo,1));
							int cancelCnt = otherInfo.getTaskCancleCnt() == null ? 0 : otherInfo.getTaskCancleCnt();
							otherInfo.setTaskCancleCnt(cancelCnt+1);
							userInfoMapper.updateByPrimaryKeySelective(otherInfo);
							
							//消息推送
							JSONObject object = new JSONObject();
					        object.put("title", "任务自动取消通知");
					        object.put("content", "由于您超过24小时未处理对方的任务取消请求，系统自动取消成功，扣除您任务经验3分");
					        object.put("type", 5);
					        object.put("paramId", taskInfo.getId());
					        
							AppPush.sendPush(object,otherInfo.getUserPhone().split(","));
							
							SmsSendUtil.sendSmsNotify(otherInfo.getId(), taskId.toString(), 5, "由于您超过24小时未处理对方的任务取消请求，系统自动取消成功，扣除您任务经验3分");
							
							//消息推送
					        object.put("content", "由于对方24小时未处理您的任务取消请求，系统自动取消成功");
					        
							AppPush.sendPush(object,userInfo.getUserPhone().split(","));
							
							SmsSendUtil.sendSmsNotify(userInfo.getId(), taskId.toString(), 5, "由于对方24小时未处理您的任务取消请求，系统自动取消成功");
							
							//从redis缓存中删除
							TaskRedisUtil.delTaskInfo(taskId.toString());
							taskTimertask t=new taskTimertask();
							t.setTaskId(taskId);
							t.setType(1);
							t.setUserId(userId);
							t.taskend();
							infoMap.put("resultCode", Constants.SUCCESS);
							infoMap.put("resultDesc", Constants.SUCCESS_DESC);
							return infoMap;
			        	}else{
			        		infoMap.put("resultCode", Constants.FAIL);
			        		infoMap.put("resultDesc", "您上次的取消请求对方尚未处理");
			        		return infoMap;
			        	}
			        }else{
			        	TaskCancelFlow flow = new TaskCancelFlow();
						flow.setFlowId(UUID.randomUUID().toString().replace("-", ""));
						flow.setFromId(userId);
						flow.setIsFinish(0);
						flow.setSendTime(new Date());
						flow.setTaskId(taskId);
						flow.setToid(taskInfo.getUserId());
						taskCancelFlowMapper.insertSelective(flow);
						
						String from = otherInfo.getUserPhone().toString();
						//环信发送消息
						JSONObject object = new JSONObject();
						object.put("from", from);
				        object.put("title", "任务取消通知");
				        object.put("type", 2);
				        object.put("paramId", taskInfo.getId());
				        object.put("content", "双方协商取消任务");
				        
						AppPush.sendPush(object,otherInfo.getUserPhone().split(","));
						
						JsonNodeFactory factory = new JsonNodeFactory(false);
				        String targetTypeus = "users";
				        ObjectNode ext = factory.objectNode();
				        ArrayNode targetusers = factory.arrayNode();
				        targetusers.add(userInfo.getUserPhone());
				        ObjectNode cmdmsg = factory.objectNode();
				        cmdmsg.put("action", object.toJSONString());
				        cmdmsg.put("type","cmd");
				        ObjectNode sendTxtMessageusernode = EasemobMessages.sendMessages(targetTypeus, targetusers, cmdmsg, from, null);
				        
						SmsSendUtil.sendSmsNotify(userId,otherInfo.getId().toString(), taskInfo.getId().toString(), 2, "双方协商取消任务!");
						
						taskTimertask t=new taskTimertask();
						t.setTaskId(taskId);
						t.setType(1);
						t.setUserId(userId);
						t.taskend();
				        infoMap.put("resultCode", Constants.SUCCESS);
						infoMap.put("resultDesc", Constants.SUCCESS_DESC);
						return infoMap;
			        }
				}
			}
		}else if(taskInfo.getTaskStatus() == 3 || taskInfo.getTaskStatus() == 4 || taskInfo.getTaskStatus() == 5){
			/*taskInfo.setTaskStatus(6);
			taskInfoMapper.updateByPrimaryKey(taskInfo);
			
			//从redis缓存中删除
			TaskRedisUtil.delTaskInfo(taskId.toString());*/
		}
		infoMap.put("resultCode", Constants.SUCCESS);
		infoMap.put("resultDesc", Constants.SUCCESS_DESC);
		return infoMap;
	}
	
	public LinkedHashMap<String,Object> cancelTaskInfo_refuse(TaskInfo taskInfo,String userId,Integer taskId,Integer type,Integer endtype){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		//TODO 短信模版ID
		final String SMSTaskFromID ="42897";
		if(taskInfo.getUserId().equals(userId)){//发布人同意或者拒绝，向参与人推送消息
			
			UserInfo otherInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getOtherUserId());
			
			UserInfo uInfo = userInfoMapper.selectByPrimaryKey(userId);
			
			TaskCancelFlowExample example = new TaskCancelFlowExample();
	        com.jsz.peini.bean.task.TaskCancelFlowExample.Criteria criteria = example.createCriteria();
	        criteria.andFromIdEqualTo(taskInfo.getOtherUserId());
	        criteria.andToidEqualTo(userId);
	        criteria.andTaskIdEqualTo(taskId);
	        criteria.andIsFinishEqualTo(0);
	        List<TaskCancelFlow> flowList = taskCancelFlowMapper.selectByExample(example);
	        OrderSellerExample orSellerExample = new OrderSellerExample();
	        if(flowList.size() > 0){
	        	if(type == 1){
	        		taskInfo.setTaskStatus(5);
	        		taskInfo.setTaskOtherStatus(5);
					taskInfo.setTaskCancleTime(new Date());
					taskInfo.setTaskCancleType(2);
					taskInfo.setCancelUserId(taskInfo.getOtherUserId());					
					taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
					
					//更新信用值
					UserInfo userInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
					int taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
					if (taskNum-3 >= 1000) {
						userInfo.setTaskNum(1000);
					}else{
						userInfo.setTaskNum(taskNum-3);
					}
					userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
					userInfoMapper.updateByPrimaryKeySelective(userInfo);
					
					com.jsz.peini.bean.order.OrderSellerExample.Criteria orCriteria = orSellerExample.createCriteria();
					orCriteria.andSellerIdEqualTo((long)taskInfo.getSellerInfoId());
					orCriteria.andOrderTypeEqualTo(1);
					orCriteria.andTaskIdEqualTo((long)taskId);
					orCriteria.andOrderStatusLessThanOrEqualTo(1);
					List<OrderSeller> list = orderSellerMapper.selectByExample(orSellerExample);
					if(list.size() > 0){
						OrderSeller orderSeller = list.get(0);
						orderSeller.setOrderStatus(-1);
						orderSellerMapper.updateByPrimaryKey(orderSeller);
					}
	        	}
	        	
	        	TaskCancelFlow hisFlow = flowList.get(0);
	        	
	        	hisFlow.setIsFinish(1);
				hisFlow.setRecvTime(new Date());
				taskCancelFlowMapper.updateByPrimaryKeySelective(hisFlow);
				JSONObject object = new JSONObject();
				object.put("title", "系统消息");
				object.put("paramId", taskInfo.getId());
				
	        	if (endtype==null) {
					//发送环信消息
	        		object.put("title", "任务取消通知");
	        		object.put("type", 8);
	        		object.put("paramId", taskInfo.getId());
	        		String content = "";
	        		if(type == 0){
	        			content = "“"+taskInfo.getSellerInfoName()+"”任务取消失败！对方未同意，看TA这么有诚意，给个机会呗，相逢即是缘~";
	        			object.put("content", content);
	        			
	        			AppPush.sendPush(object,otherInfo.getUserPhone().toString().split(","));
	        			SmsSendUtil.sendSmsNotify(taskInfo.getOtherUserId(), taskId.toString(), 8, content);
	        		}else{
	        			content = "“"+taskInfo.getSellerInfoName()+"”任务取消成功！经您双方协商，均已同意放弃本次任务，我们将会收回发任务时赠送的任务积分3分~不要气馁，让我们继续约起来~下一个可能更好哦~";
	        			object.put("content", content);
	        			
	        			AppPush.sendPush(object,uInfo.getUserPhone().toString().split(","));
	        			SmsSendUtil.sendSmsNotify(uInfo.getId(), taskId.toString(), 8, content);
	        			
	        			content = "“"+taskInfo.getSellerInfoName()+"”任务取消成功！经您双方协商，均已同意放弃本次任务~不要气馁，让我们继续约起来~下一个可能更好哦";
	        			object.put("content", content);
	        			
	        			AppPush.sendPush(object,otherInfo.getUserPhone().toString().split(","));
	        			SmsSendUtil.sendSmsNotify(otherInfo.getId(), taskId.toString(), 8, content);
	        		}
	        	}else if(endtype==1){
	        		object.put("type", 108);
			        object.put("content","由于您发布的“"+taskInfo.getSellerInfoName()+"”任务已超过任务时间仍未被接取，系统已为您自动取消并收回发任务时赠送的任务经验3分，不要气馁，让我们继续约起来~下一个可能更好哦");
			        UserInfo u1 = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
					AppPush.sendPush(object,u1.getUserPhone().toString().split(","));
					
					SmsSendUtil.sendSmsNotify(taskInfo.getUserId(), taskId.toString(), 108, "由于您发布的“"+taskInfo.getSellerInfoName()+"”任务已超过任务时间仍未被接取，系统已为您自动取消并收回发任务时赠送的任务经验3分，不要气馁，让我们继续约起来~下一个可能更好哦");
	        	}else if(endtype==2){
	        		//发送环信消息
	        		object.put("type", 109);
			        object.put("content", "由于您发布的“"+taskInfo.getSellerInfoName()+"”任务超过一天仍未有人付款，系统自动判定为任务失败并收回发任务时赠送的任务经验3分，不要气馁，让我们继续约起来~下一个可能更好哦");
			        UserInfo u1 = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
					AppPush.sendPush(object,u1.getUserPhone().toString().split(","));
					UserInfo u2 = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
					object.put("content", "由于您参加的“"+taskInfo.getSellerInfoName()+"”任务超过一天仍未有人付款，系统自动判定为任务失败，不要气馁，让我们继续约起来~下一个可能更好哦~");
					AppPush.sendPush(object,u2.getUserPhone().split(","));
					
					SmsSendUtil.sendSmsNotify(taskInfo.getUserId(), taskId.toString(), 109, "由于您发布的“"+taskInfo.getSellerInfoName()+"”任务超过一天仍未有人付款，系统自动判定为任务失败并收回发任务时赠送的任务经验3分，不要气馁，让我们继续约起来~下一个可能更好哦");
					
					SmsSendUtil.sendSmsNotify(taskInfo.getOtherUserId(), taskId.toString(), 109, "由于您参加的“"+taskInfo.getSellerInfoName()+"”任务超过一天仍未有人付款，系统自动判定为任务失败，不要气馁，让我们继续约起来~下一个可能更好哦~");
	        	}
				if (type==1) {
					SellerInfo sellerInfo=sellerInfoMapper.getSellerInfoById(taskInfo.getSellerInfoId());
					if(StringUtils.isNotBlank(sellerInfo.getSmsType()) && sellerInfo.getSmsType().indexOf("2")>=0){
						List<OrderSeller> list = orderSellerMapper.selectByExample(orSellerExample);
						if(list.size() > 0){
							OrderSeller orderSeller = list.get(0);
							orderSeller.setOrderStatus(-1);
							orderSellerMapper.updateByPrimaryKey(orderSeller);
						if (sellerInfo.getWeathersms()==1) {
							if (sellerInfo.getSmsText()!=null) {
								String param=orderSeller.getOrderCode()+","+sellerInfo.getSellerName()+"（"+sellerInfo.getDistrictName()+"店）,";
								SmsSend.sendByTask(sellerInfo.getSmsText(), param, SMSTaskFromID);
							}
						}
						}
					}
				}
		        
		        infoMap.put("resultCode", Constants.SUCCESS);
				infoMap.put("resultDesc", Constants.SUCCESS_DESC);
				return infoMap;
	        }else{
	        	infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "已经操作过了，请勿重复操作");
				return infoMap;
	        }
		}else{//参与人同意或者拒绝
			UserInfo otherInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
			UserInfo uInfo = userInfoMapper.selectByPrimaryKey(userId);
			
			TaskCancelFlowExample example = new TaskCancelFlowExample();
	        com.jsz.peini.bean.task.TaskCancelFlowExample.Criteria criteria = example.createCriteria();
	        criteria.andFromIdEqualTo(taskInfo.getUserId());
	        criteria.andToidEqualTo(userId);
	        criteria.andTaskIdEqualTo(taskId);
	        criteria.andIsFinishEqualTo(0);
	        List<TaskCancelFlow> flowList = taskCancelFlowMapper.selectByExample(example);
	        if(flowList.size() > 0){
	        	if(type == 1){
	        		taskInfo.setTaskStatus(5);
	        		taskInfo.setTaskOtherStatus(5);
					taskInfo.setTaskCancleTime(new Date());
					taskInfo.setTaskCancleType(2);
					taskInfo.setCancelUserId(taskInfo.getUserId());					
					taskInfoMapper.updateByPrimaryKeySelective(taskInfo);
					
					//更新信用值
					UserInfo userInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
					int taskNum = userInfo.getTaskNum() == null ? 0 : userInfo.getTaskNum();
					if (taskNum-3 >= 1000) {
						userInfo.setTaskNum(1000);
					}else{
						userInfo.setTaskNum(taskNum-3);
					}
					userInfo.setReputation(PeiniUtils.getCredit(userInfo,1));
					userInfoMapper.updateByPrimaryKeySelective(userInfo);
	        	}
	        	
	        	TaskCancelFlow hisFlow = flowList.get(0);
	        	
	        	hisFlow.setIsFinish(1);
				hisFlow.setRecvTime(new Date());
				taskCancelFlowMapper.updateByPrimaryKeySelective(hisFlow);
				
				JSONObject object = new JSONObject();
				object.put("title", "任务取消通知");
        		object.put("type", 8);
        		object.put("paramId", taskInfo.getId());
        		String content = "";
        		if(type == 0){
        			content = "“"+taskInfo.getSellerInfoName()+"”任务取消失败！对方未同意，看TA这么有诚意，给个机会呗，相逢即是缘~";
        			object.put("content", content);
        			
        			AppPush.sendPush(object,otherInfo.getUserPhone().toString().split(","));
        			SmsSendUtil.sendSmsNotify(otherInfo.getId(), taskId.toString(), 8, content);
        		}else{
        			content = "“"+taskInfo.getSellerInfoName()+"”任务取消成功！经您双方协商，均已同意放弃本次任务，我们将会收回发任务时赠送的任务积分3分~不要气馁，让我们继续约起来~下一个可能更好哦~";
        			object.put("content", content);
        			
        			AppPush.sendPush(object,otherInfo.getUserPhone().toString().split(","));
        			SmsSendUtil.sendSmsNotify(otherInfo.getId(), taskId.toString(), 8, content);
        			
        			content = "“"+taskInfo.getSellerInfoName()+"”任务取消成功！经您双方协商，均已同意放弃本次任务~不要气馁，让我们继续约起来~下一个可能更好哦";
        			object.put("content", content);
        			
        			AppPush.sendPush(object,uInfo.getUserPhone().toString().split(","));
        			SmsSendUtil.sendSmsNotify(userId, taskId.toString(), 8, content);
        		}
	        	
				OrderSellerExample orSellerExample = new OrderSellerExample();
				com.jsz.peini.bean.order.OrderSellerExample.Criteria orCriteria = orSellerExample.createCriteria();
				orCriteria.andSellerIdEqualTo((long)taskInfo.getSellerInfoId());
				orCriteria.andOrderTypeEqualTo(1);
				orCriteria.andTaskIdEqualTo((long)taskId);
				orCriteria.andOrderStatusLessThanOrEqualTo(1);
				List<OrderSeller> list = orderSellerMapper.selectByExample(orSellerExample);
				if (type==1) {
					SellerInfo sellerInfo=sellerInfoMapper.getSellerInfoById(taskInfo.getSellerInfoId());
					if(StringUtils.isNotBlank(sellerInfo.getSmsType()) && sellerInfo.getSmsType().indexOf("2")>=0){
						if(list.size() > 0){
							OrderSeller orderSeller = list.get(0);
							orderSeller.setOrderStatus(-1);
							orderSellerMapper.updateByPrimaryKey(orderSeller);
						if (sellerInfo.getWeathersms()==1) {
							if (sellerInfo.getSmsText()!=null) {
								String param=orderSeller.getOrderCode()+","+sellerInfo.getSellerName()+"（"+sellerInfo.getDistrictName()+"店）,";
								SmsSend.sendByTask(sellerInfo.getSmsText(), param, SMSTaskFromID);
							}
						}
						}
					}
				}
		        
		        infoMap.put("resultCode", Constants.SUCCESS);
				infoMap.put("resultDesc", Constants.SUCCESS_DESC);
				return infoMap;
	        }else{
	        	infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "已经操作过了，请勿重复操作");
				return infoMap;
	        }
		}
	}
	
	public HashMap<String,Object> getTaskLast(String userId){
		HashMap<String,Object> taskMap = taskInfoMapper.getTaskLast(userId);
		return taskMap;
	}
	
	public int getCancelNum(String userId){
		int result = 0;
		int allnum = taskInfoMapper.getAllTaskCountByUserId(userId);
		int cancelnum = taskInfoMapper.getCancelCountByUserId(userId);
		if(allnum!=0){
			result = cancelnum*100/allnum;
		}
		return result;
	}
	
	public List<LinkedHashMap<String,Object>> getTaskInfoByUserId(TaskInfo taskInfo){
		List<LinkedHashMap<String,Object>> TaskInfoByUserId=taskInfoMapper.getTaskInfoByUserId(taskInfo);
		return TaskInfoByUserId;
	}
	
	/**
	 * 我的任务
	 */
	public List<Map<String,Object>> getUserTaskInfoList(String userId, String type, String status){
		List<Map<String,Object>> myTaskList = taskInfoMapper.selectMyTask(userId,type,status);
		List<Map<String,Object>> myPartyList = partyInfoMapper.selectMyParty(userId, type,status);
		myTaskList.addAll(myPartyList);
		myTaskList.sort(new TaskComparator());
		return myTaskList;
	}
	
	/**
	 * 多任务列表
	 */
	public List<Map<String,Object>> getMultiTaskList(String taskIds, String partyIds){
		List<Map<String,Object>> myTaskList = taskInfoMapper.selectTasksByIds(taskIds);
		List<Map<String,Object>> myPartyList = partyInfoMapper.selectPartiesByIds(partyIds);
		myTaskList.addAll(myPartyList);
		myTaskList.sort(new TaskComparator());
		return myTaskList;
	}
	
	public List<CommonTaskInfo> searchTasks(TaskInMapSearchVo vo){
		List<CommonTaskInfo> result = new ArrayList<CommonTaskInfo>();
		List<Map<String,Object>> partyList = partyInfoMapper.selectInDistance(vo);
		for(Map<String,Object> p : partyList){
			CommonTaskInfo c = new CommonTaskInfo();
			c.setId((int)p.get("id"));
			c.setImage((String)p.get("image"));
			c.setSellerType((int)p.get("sellerSmallType"));
			c.setSex((int)p.get("sex"));
			c.setType(2);
			c.setUserId((String)p.get("userId"));
			c.setXpoint(((Double)p.get("xpoint")).toString());
			c.setYpoint(((Double)p.get("ypoint")).toString());
			result.add(c);
		}
		List<Map<String,Object>> taskList = taskInfoMapper.selectInDistance(vo);
		for(Map<String,Object> t : taskList){
			CommonTaskInfo c = new CommonTaskInfo();
			c.setId((int)t.get("id"));
			c.setImage((String)t.get("image"));
			c.setSellerType((int)t.get("sellerSmallType"));
			c.setSex((int)t.get("sex"));
			c.setType(1);
			c.setUserId((String)t.get("userId"));
			c.setXpoint((String)t.get("xpoint"));
			c.setYpoint((String)t.get("ypoint"));
			result.add(c);
		}
		return result;
	}
	
}

class TaskComparator implements Comparator<Map<String,Object>>{
	@Override
	public int compare(Map<String,Object> o1, Map<String,Object> o2) {
		return ((Date)o2.get("appointedTime")).compareTo((Date)o1.get("appointedTime"));
	}
	
}
